package org.example.java.util.concurrency.threadlocal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * 它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题
 *
 *
 * Created by Juntao.Zhang on 2014/9/10.
 */
public class Dao {
  //①使用ThreadLocal保存Connection变量
  private static ThreadLocal<Connection> connThreadLocal = new ThreadLocal<>();

  public static Connection getConnection() throws Exception {
    //②如果connThreadLocal没有本线程对应的Connection创建一个新的Connection，
    //并将其保存到线程本地变量中。
    if (connThreadLocal.get() == null) {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:db", "username", "password");
      connThreadLocal.set(conn);
      return conn;
    } else {
      return connThreadLocal.get();//③直接返回线程本地变量
    }
  }

  public void addEntity() throws Exception {
    //④从ThreadLocal中获取线程对应的Connection
    Statement stat = getConnection().createStatement();
  }
}
